package com.tiamosu.navigation.demo.ext

import android.os.Bundle
import androidx.annotation.IdRes
import androidx.navigation.NavOptions
import androidx.navigation.Navigator
import com.tiamosu.navigation.demo.R
import com.tiamosu.navigation.demo.base.BaseFragment
import com.tiamosu.navigation.ext.navigate
import com.tiamosu.navigation.ext.popBackStack

/**
 * @author tiamosu
 * @date 2021/5/11.
 */

/**
 * Fragment页面跳转
 * @param resId 操作ID或要导航到的目标ID
 * @param popUpToId 退出栈到指定目标ID
 * @param popUpToInclusive 给定的目的地是否也弹出
 * @param singleTop 是否进行栈顶复用
 * @param navigatorExtras 额外内容传递给导航器，可配置页面共享元素等
 * @param interval 设置防抖间隔时间，单位毫秒
 * @param args 传递给目的地的参数
 */
fun BaseFragment.jumpFragment(
    @IdRes resId: Int = -1,
    @IdRes popUpToId: Int = -1,
    popUpToInclusive: Boolean = false,
    singleTop: Boolean = false,
    navigatorExtras: Navigator.Extras? = null,
    interval: Long = 500,
    args: Bundle? = null,
) {

    fun start() {
        if (resId == -1) {
            if (popUpToId != -1) {
                popBackStack(popUpToId, popUpToInclusive)
            }
            return
        }
        val navOptions = NavOptions.Builder()
            .setEnterAnim(R.anim.fly_fragment_slide_enter)
            .setExitAnim(R.anim.fly_fragment_slide_exit)
            .setPopEnterAnim(R.anim.fly_fragment_slide_pop_enter)
            .setPopExitAnim(R.anim.fly_fragment_slide_pop_exit)
            .apply {
                if (popUpToId != -1) {
                    setPopUpTo(popUpToId, popUpToInclusive)
                }
            }
            .setLaunchSingleTop(singleTop)
            .build()

        navigate(resId, args, navOptions, navigatorExtras, interval = interval)
    }

    if (isFlySupportVisible()) {
        start()
        return
    }
    jumpRunnable = Runnable { start() }
}